<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-input
          v-model="listQuery.name"
          placeholder="居委会名称"
          style="width: 200px"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button class="filter-item" type="primary" @click="handleFilter">
          搜索
        </el-button>
        <el-button class="filter-item" type="primary" @click="handleCreate">
          添加居委会
        </el-button>
      </div>

      <el-table
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="居委会名称" prop="name" align="center" />
        <el-table-column label="地址" prop="address" align="center" />
        <el-table-column label="联系电话" prop="contactPhone" align="center" />
        <el-table-column label="创建时间" prop="createdAt" align="center" />
        <el-table-column label="操作" align="center" width="430">
          <template #default="{ row }">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-button type="success" size="mini" @click="handleDetails(row)">
              小区详情
            </el-button>
            <el-button type="danger" size="mini" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="居委会名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="temp.address" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="temp.contactPhone" />
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input v-model="temp.description" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取消 </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <!-- 小区详情弹窗 -->
    <el-dialog title="小区列表" v-model="detailsDialogVisible" width="70%">
      <el-table
        v-loading="detailsLoading"
        :data="complexes"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="小区名称" prop="name" align="center" />
        <el-table-column label="地址" prop="address" align="center" />
        <el-table-column label="描述" prop="description" align="center" />
        <el-table-column label="创建时间" prop="createdAt" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="mini"
              @click="handleComplexDetails(row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button type="primary" @click="detailsDialogVisible = false">
          关闭
        </el-button>
      </template>
    </el-dialog>

    <!-- 小区详细信息弹窗 -->
    <el-dialog
      title="小区详细信息"
      v-model="complexDetailDialogVisible"
      width="50%"
    >
      <el-descriptions v-loading="complexDetailLoading" :column="1" border>
        <el-descriptions-item label="小区名称">
          {{ complexDetail?.name }}
        </el-descriptions-item>
        <el-descriptions-item label="地址">
          {{ complexDetail?.address }}
        </el-descriptions-item>
        <el-descriptions-item label="描述">
          {{ complexDetail?.description }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ complexDetail?.createdAt }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ complexDetail?.updatedAt }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import {
  getNeighborhoodList,
  createNeighborhood,
  updateNeighborhood,
  deleteNeighborhood,
  getCommitteeComplexes,
  getCommunityDetail,
} from "@/api/community";

export default {
  name: "Neighborhood",
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined,
      },
      dialogVisible: false,
      dialogStatus: "",
      dialogTitle: "",
      temp: {
        id: undefined,
        name: "",
        address: "",
        contactPhone: "",
        description: "",
      },
      complexes: [],
      detailsDialogVisible: false,
      detailsLoading: false,
      complexDetail: null,
      complexDetailDialogVisible: false,
      complexDetailLoading: false,
      rules: {
        name: [
          { required: true, message: "请输入居委会名称", trigger: "blur" },
        ],
        address: [{ required: true, message: "请输入地址", trigger: "blur" }],
        contactPhone: [
          { required: true, message: "请输入联系电话", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async getList() {
      this.listLoading = true;
      try {
        const data = await getNeighborhoodList(this.listQuery);
        this.list = data.items;
        this.total = data.total;
      } catch (error) {
        console.error("获取居委会列表失败:", error);
      }
      this.listLoading = false;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: "",
        address: "",
        phone: "",
      };
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogTitle = "添加居委会";
      this.dialogVisible = true;
    },
    createData() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          try {
            await createNeighborhood(this.temp);
            this.dialogVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000,
            });
            this.getList();
          } catch (error) {
            console.error("创建居委会失败:", error);
          }
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row);
      this.dialogStatus = "update";
      this.dialogTitle = "编辑居委会";
      this.dialogVisible = true;
    },
    updateData() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          try {
            await updateNeighborhood(this.temp.id, this.temp);
            this.dialogVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000,
            });
            this.getList();
          } catch (error) {
            console.error("更新居委会失败:", error);
          }
        }
      });
    },
    async handleDelete(row) {
      try {
        await this.$confirm("确认删除该居委会吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        await deleteNeighborhood(row.id);
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000,
        });
        this.getList();
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除居委会失败:", error);
        }
      }
    },
    async handleDetails(row) {
      this.detailsLoading = true;
      try {
        const data = await getCommitteeComplexes(row.id);
        this.complexes = data;
        this.detailsDialogVisible = true;
      } catch (error) {
        console.error("获取小区列表失败:", error);
        this.$notify({
          title: "错误",
          message: "获取小区列表失败",
          type: "error",
          duration: 2000,
        });
      }
      this.detailsLoading = false;
    },
    async handleComplexDetails(row) {
      this.complexDetailLoading = true;
      try {
        const data = await getCommunityDetail(row.id);
        this.complexDetail = data;
        this.complexDetailDialogVisible = true;
      } catch (error) {
        console.error("获取小区详情失败:", error);
        this.$notify({
          title: "错误",
          message: "获取小区详情失败",
          type: "error",
          duration: 2000,
        });
      }
      this.complexDetailLoading = false;
    },
  },
};
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
</style>
